
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <sys/fcntl.h>
#include <sys/epoll.h>
#include <netinet/tcp.h> // TCP_NODELAY需要包含这个头文件。
#include "InetAddress.h"
#include "Socket.h"
#include "Epoll.h"
#include"Channel.h"
#include"EventLoop.h"
void setnonblocking(int fd)
{
    int event = fcntl(fd, F_GETFL);
    if (event == 0)
    {
        return;
    }
    fcntl(fd, F_SETFL, event | O_NONBLOCK);
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        printf("usage: ./tcpepoll ip port\n");
        printf("example: ./tcpepoll 127.0.0.1 8080\n");
        return -1;
    }

    Socket servsock(createnonblocking());
    
    servsock.setkeepalive(true);
    servsock.setreuseaddr(true);
    servsock.setreuseport(true);
    servsock.settcpnodelay(true);
    std::string ip = argv[1];
    uint16_t port = atoi(argv[2]);
    InetAddress serveraddr(ip, port);
    servsock.bind(serveraddr);
    servsock.listen();
    std::vector<epoll_event> evs;

    // int epfd = epoll_create(1);
    // Epoll epoll;
    EventLoop loop;
    Channel *servchannel=new Channel(loop.getEpfd(),servsock.fd());  
    servchannel->setreadcallback(std::bind(&Channel::newConnection,servchannel,&servsock));
    servchannel->enablereading(); 
    servchannel->setinepoll();
    
    loop.run();
    // while (true)
    // {
    //     std::vector<Channel*> channels = epoll.loop(); 
    //     for (auto &ch:channels)
    //     {
    //         ch->handleevent(); 
    //     }      
    // }
    return 0;
}